import '../models/notification_message.dart';
import 'http_client.dart';

/// 通知API服务 - 与后端Redis通知系统交互
class NotificationApiService {
  static final NotificationApiService _instance = NotificationApiService._internal();
  factory NotificationApiService() => _instance;
  NotificationApiService._internal();

  final HttpClient _httpClient = HttpClient();

  /// 获取用户的所有通知消息
  Future<Map<String, dynamic>> getMessages({
    int pageNum = 1,
    int pageSize = 20,
  }) async {
    try {
      final response = await _httpClient.get(
        '/pond/app/notifications/messages',
        queryParameters: {
          'pageNum': pageNum.toString(),
          'pageSize': pageSize.toString(),
        },
      );

      if (response['code'] == 200) {
        final List<dynamic> messagesData = response['data'] ?? [];
        final List<NotificationMessage> messages = messagesData.map((data) {
          return _parseRedisMessage(data);
        }).toList();

        return {
          'success': true,
          'data': messages,
          'total': messages.length,
        };
      } else {
        return {
          'success': false,
          'message': response['msg'] ?? '获取消息失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 获取未读消息数量
  Future<Map<String, dynamic>> getUnreadCount() async {
    try {
      final response = await _httpClient.get('/pond/app/notifications/unread-count');

      if (response['code'] == 200) {
        return {
          'success': true,
          'data': response['data'] ?? 0,
        };
      } else {
        return {
          'success': false,
          'message': response['msg'] ?? '获取未读数量失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 标记消息为已读
  Future<Map<String, dynamic>> markAsRead(String messageId, int index) async {
    try {
      final response = await _httpClient.post(
        '/pond/app/notifications/mark-read',
        data: {
          'messageId': messageId,
          'index': index,
        },
      );

      if (response['code'] == 200) {
        return {
          'success': true,
          'message': response['data'] ?? '标记成功',
        };
      } else {
        return {
          'success': false,
          'message': response['msg'] ?? '标记失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 标记所有消息为已读
  Future<Map<String, dynamic>> markAllAsRead() async {
    try {
      final response = await _httpClient.post('/pond/app/notifications/mark-all-read');

      if (response['code'] == 200) {
        return {
          'success': true,
          'message': response['data'] ?? '全部标记成功',
        };
      } else {
        return {
          'success': false,
          'message': response['msg'] ?? '标记失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 删除消息
  Future<Map<String, dynamic>> deleteMessage(int index) async {
    try {
      final response = await _httpClient.delete(
        '/pond/app/notifications/delete',
        queryParameters: {
          'index': index.toString(),
        },
      );

      if (response['code'] == 200) {
        return {
          'success': true,
          'message': response['data'] ?? '删除成功',
        };
      } else {
        return {
          'success': false,
          'message': response['msg'] ?? '删除失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 清空所有消息
  Future<Map<String, dynamic>> clearAllMessages() async {
    try {
      final response = await _httpClient.delete('/pond/app/notifications/clear-all');

      if (response['code'] == 200) {
        return {
          'success': true,
          'message': response['data'] ?? '清空成功',
        };
      } else {
        return {
          'success': false,
          'message': response['msg'] ?? '清空失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 发送通知消息
  Future<Map<String, dynamic>> sendNotification({
    required String toUserId,
    required String notificationType,
    required String title,
    required String content,
    String? senderName,
    String? senderId,
    String? targetId,
    String? targetType,
    String? navigationPath,
    Map<String, dynamic>? navigationParams,
  }) async {
    try {
      final response = await _httpClient.post(
        '/pond/app/notifications/send',
        data: {
          'toUserId': toUserId,
          'notificationType': notificationType,
          'title': title,
          'content': content,
          'senderName': senderName,
          'senderId': senderId,
          'targetId': targetId,
          'targetType': targetType,
          'navigationPath': navigationPath,
          'navigationParams': navigationParams,
        },
      );

      if (response['code'] == 200) {
        return {
          'success': true,
          'message': response['data'] ?? '发送成功',
        };
      } else {
        return {
          'success': false,
          'message': response['msg'] ?? '发送失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 解析Redis消息格式
  NotificationMessage _parseRedisMessage(Map<String, dynamic> redisData) {
    try {
      // Redis消息格式: {"content": {...}, "read": false, "index": 0, "messageId": "msg_1_0"}
      final content = redisData['content'] as Map<String, dynamic>? ?? {};
      final isRead = redisData['read'] as bool? ?? false;
      final index = redisData['index'] as int? ?? 0;
      final messageId = redisData['messageId'] as String? ?? '';

      return NotificationMessage(
        id: messageId,
        type: content['notificationType'] ?? 'system',
        title: content['title'] ?? '通知',
        content: content['content'] ?? '',
        senderName: content['senderName'],
        senderId: content['senderId']?.toString(),
        targetId: content['targetId']?.toString(),
        targetType: content['targetType'],
        navigationPath: content['navigationPath'],
        navigationParams: content['navigationParams'] as Map<String, dynamic>?,
        extraData: {
          ...content,
          'index': index,
          'messageId': messageId,
        },
        timestamp: content['timestamp'] != null
            ? DateTime.fromMillisecondsSinceEpoch(content['timestamp'])
            : DateTime.now(),
        isRead: isRead,
        isOffline: true, // 从Redis获取的都标记为离线消息
      );
    } catch (e) {
      // 返回一个默认的错误消息
      return NotificationMessage(
        id: 'error_${DateTime.now().millisecondsSinceEpoch}',
        type: 'system',
        title: '消息解析错误',
        content: '无法解析的消息格式',
        timestamp: DateTime.now(),
        isRead: false,
        isOffline: true,
      );
    }
  }
}